import { Form, Input, Modal, Select, AutoComplete } from 'antd'
import PropTypes from 'prop-types'
import { nameExist, findOneUser, register, updateUser } from '@/api/user'
import { useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import md5 from 'md5'

const UserForm = (props) => {
  const dictionary = useSelector((state) => state.data.dictionary)
  const roleList = dictionary.role.data
  const genderList = dictionary.gender.data
  const [options, setOptions] = useState([])

  const [form] = Form.useForm()

  const checkNameExist = async (username) => {
    if (username) {
      const { data } = await nameExist({ username })
      if (data) {
        form.setFields([
          {
            name: 'username',
            errors: ['用户名已存在']
          }
        ])
      }
    }
  }

  useEffect(() => {
    async function fetchData () {
      if (props.user_id) {
        const { data } = await findOneUser({
          user_id: props.user_id
        })
        form.setFieldsValue(data)
      }
    }
    fetchData()
  }, [props.user_id])

  const onOk = async () => {
    const values = await form.validateFields()
    console.log('Success:', values)
    if (props.user_id) {
      //更新
      await updateUser({
        id: props.user_id,
        ...values
      })
    } else {
      //注册
      await register({
        password: md5('123465'),
        ...values
      })
    }
    props.onOk()
  }

  const handleSearch = (value) => {
    setOptions(() => {
      if (!value || value.includes('@')) {
        return []
      }
      return ['163.com', 'qq.com'].map((domain) => ({
        value: `${value}@${domain}`,
        label: `${value}@${domain}`
      }))
    })
  }

  const onChange = (e) => {
    const value = e.target.value.replace(/[^0-9]/g, '')
    form.setFieldsValue({ phone_number: value })
  }

  const isDetail = Boolean(props.title.includes('详情'))
  const isEdit = Boolean(props.title.includes('编辑'))
  return (
    <Modal
      title={props.title}
      open={props.visible}
      maskClosable={false}
      footer={isDetail ? null : undefined}
      cancelText="取消"
      okText="确定"
      onCancel={props.onCancel}
      onOk={onOk}
    >
      <Form
        form={form}
        autoComplete="off"
        disabled={isDetail}
        initialValues={{
          password: '123456',
          status: 1
        }}
        labelCol={{ span: 4 }}
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名'
            }
          ]}
        >
          <Input disabled={isDetail || isEdit} onBlur={() => checkNameExist(form.getFieldValue('username'))} />
        </Form.Item>
        <Form.Item name="email" label="邮箱">
          <AutoComplete onSearch={handleSearch} options={options} />
        </Form.Item>
        <Form.Item
          name="phone_number"
          label="手机号"
          rules={[
            {
              message: '请输入正确的手机号',
              pattern: /^1[3-9]\d{9}$/
            }
          ]}
        >
          <Input maxLength={11} onChange={onChange} />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select
            options={[
              {
                value: 1,
                label: '启用'
              },
              {
                value: 0,
                label: '禁用'
              }
            ]}
          />
        </Form.Item>
        <Form.Item name="role" label="角色">
          <Select
            options={roleList}
          />
        </Form.Item>
        <Form.Item name="avatar" label="头像">
          <Input />
        </Form.Item>
        <Form.Item name="gender" label="性别">
          <Select
            options={genderList}
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}

UserForm.propTypes = {
  user_id: PropTypes.number,
  title: PropTypes.string.isRequired,
  visible: PropTypes.bool.isRequired,
  onCancel: PropTypes.func.isRequired,
  onOk: PropTypes.func.isRequired
}

export default UserForm